package com.design.pages;

import com.design.fill.FillBox;
import com.design.game.MoveBox;
import com.design.method.error.GameLogError;
import com.design.method.error.ParserError;
import com.design.util.Console;
import com.design.util.moveBox.GameLog;
import com.design.util.moveBox.MapMethod;
import com.design.util.moveBox.MapParser;
import com.design.util.moveBox.Next;
import com.design.window.Route;
import java.awt.*;
import java.io.File;

public class PlayMoveBox extends Route {
    private MoveBox moveBox;
    private GameLog gameLog;
    private final File file;
    public PlayMoveBox(File file) throws ParserError {
        super(null,800,800,null,"推阔子开始");
        this.file = file;
    }
    @Override
    protected void keyReleased(char key) {
        if(this.gameLog.moving){
            return;
        }
        int[] direction = Next.switchDirection(key);
        if(direction != null){
            if(this.moveBox.movePlayer(direction)){
                this.gameLog.addLog(direction);
                this.refill();
            }
            return;
        }
        switch(key){
            case 'r':
                this.gameLog.remove();
//                this.moveBo
                this.restart();
                return;
        }

    }
    @Override
    public boolean before() {
        MapMethod method;
        try{
             method = MapParser.parser(this.file);
        } catch (ParserError parserError) {
            parserError.printStackTrace();
            return false;
        }
        this.moveBox = new MoveBox(method);
        this.gameLog = new GameLog(method.getLogMap());
        return true;
    }

    @Override
    protected boolean close() {//保存日志
//        if(this.moveBox)
        if(this.gameLog.moving){
            return false;
        }
        try{
            this.gameLog.save();
        } catch (GameLogError gameLogError) {
            Console.error(gameLogError.getMessage());
        }
        this.getFrame().dispose();
        return true;
    }

    @Override
    protected void run() {
        this.gameLog.run(this.getPanel(),this.moveBox);
    }

    @Override
    protected void filling(Graphics g) {
        FillBox.fill(g,moveBox.getMethod(),800);
    }
}
